#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: liang kang
@contact: gangkanli1219@gmail.com
@time: 2018/3/9 21:53
@desc: 数组图像处理的方法
"""
import numpy as np
from skimage import transform

from .tools import check_image_format


def center_crop(image, crop_shape):
    """
    中心裁剪图像

    Parameters
    ----------
    image
    crop_shape

    Returns
    -------

    """
    image, func = check_image_format(image)
    shape = image.shape
    offset = list(map(lambda x, y: (x - y) // 2, shape, crop_shape))
    max_axis = list(map(lambda x, y: x + y, offset, crop_shape))
    sub_image = image[offset[0]:max_axis[0], offset[1]:max_axis[1], :]
    return func(sub_image)


def rotate_image_and_center_crop(angle, image):
    """
    逆时针旋转一个图像 angle 度

    Parameters
    ----------
    angle: 要旋转的角度
    image: 原始图像

    Returns
    -------
    img_buf: 从旋转后的图像的中心切割出来与原始图像相同shape的图像
    offset: img_buf 相对于旋转后的图像的顶点（左上角）的起始坐标

    """
    image, func = check_image_format(image)
    shape = image.shape
    arc = angle * np.pi / 180
    post_size = (np.ceil(abs(shape[0] * np.cos(arc)) +
                         abs(shape[1] * np.sin(arc))).astype(np.int32),
                 np.ceil(abs(shape[0] * np.sin(arc)) +
                         abs(shape[1] * np.cos(arc))).astype(np.int32))
    offset = list(map(lambda x, y: (x - y) // 2, post_size, shape))
    if 0 == angle:
        img_buf = image.copy()
        img_buf = img_buf.astype(np.float32)
    else:
        img_buf = transform.rotate(image, angle,
                                   resize=True, preserve_range=True)
        img_buf = center_crop(img_buf, shape)
    return offset, func(img_buf)



